package kr.hkit.androidcomplete03.ch28_1;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import kr.hkit.androidcomplete03.R;
import kr.hkit.androidcomplete03.ch28_1.common.Item;
import kr.hkit.androidcomplete03.ch28_1.common.MyAdapter;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ListView;

public class JsonParser extends Activity {
	ListView list;
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.parser);
		list = (ListView) findViewById(R.id.orderListView);
		new ParsingXml().execute("order.json");
	}
	
	private class ParsingXml extends AsyncTask<String, Void, ArrayList<Item>>{
		ProgressDialog progressDlg;
		
		protected ArrayList<Item> doInBackground(String... params) {
			StringBuilder sb = new StringBuilder();
			String str=null;
			BufferedReader br=null;
			try {
				br = new BufferedReader(new InputStreamReader(openFileInput(params[0])));
				while((str=br.readLine()) != null){
					sb.append(str);
				}
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {br.close();}catch(IOException e) {}
			}
			return parsingXml(sb.toString());
		}

		private ArrayList<Item> parsingXml(String xml) {
			ArrayList<Item> arLists = new ArrayList<>();
			Item item=null;
			try {
				JSONArray ja = new JSONArray(xml);
				for(int i=0; i<ja.length(); i++){
					JSONObject jsonObj = ja.getJSONObject(i);
					item = new Item();
					item.setItemName(jsonObj.getString("Product"));
					item.setItemMaker(jsonObj.getString("Maker"));
					item.setItemPrice(jsonObj.getInt("Price"));
					arLists.add(item);
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
			return arLists;
		}

		protected void onPreExecute() {
			progressDlg = ProgressDialog.show(JsonParser.this, "Wait", "Xml Parsing...");
		}

		protected void onPostExecute(ArrayList<Item> result) {
			progressDlg.dismiss();
			MyAdapter adapter = new MyAdapter(JsonParser.this, result);
			list.setAdapter(adapter);		
		}
	}//end of class ParsingXml
	
}//end of class JsonParser
